import React from "react"; 
import { Spin, Modal, Empty } from "antd";
import { connect } from "dva";
import dynamic from 'umi/dynamic';
import FormTopBar from "./components/FormTopBar";
import CustomForm from "../../../components/customForm/CustomForm";
import { openNotificationWithIcon, delay, getCardChildProperties } from "../../../utils/comm";
import styles from "./index.less";

let componentLoadedResolve = null;
const lazyLoadPromise = new Promise((r) => { componentLoadedResolve = r });
const FormEditor = dynamic({ loader: async () => {
  await delay(800);
  return import('@ali-dayu/form-editor').then((data) => {
    componentLoadedResolve();
    return data;
  });
} });

const defaultMaps = {
  CustomSetterMap: {},
  CustomWidgetMap: {},
};
export const codePattern = /^[a-zA-Z_][a-zA-Z_0-9-]*$/;
export const codePatternErrMsg = '表单编码输入格式不正确（由字母、数字、下划线、中划线，且以字母或者下划线开头），请修改后保存';

const defaultFormSchema = {
  type: 'object',
  properties: {
  },
};
@connect((states) => ({
  loading: states.loading,
}))
class FormBuilder extends React.Component {
  constructor(props) {
    super(props);
    this.state = { formSchema: { ...defaultFormSchema }, formVisible: false, ...defaultMaps};
    // this.state.editable = true;
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
  }

  async componentDidMount() {
    const { CustomWidgetMap, CustomSetterMap } = await import('components/formily/form-editor/setters');
    this.setState({ CustomWidgetMap, CustomSetterMap }, () => {
      lazyLoadPromise.then(this.initFormDetail);// @ali-dayu/form-editor v0.0.10bug,必须先加载完成组件再设置value
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "FormBuilder/clearData" });
  }

  initFormDetail = () => {
    const {
      location: {
        query: { formId = "" },
      },
      dispatch,
    } = this.props;
    if (!formId) return;
    dispatch({ type: "FormBuilder/getFormDetail", payload: { formId } }).then(
      ({ errCode, errMsg, datas }) => {
        const { fields = [] } = datas;
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "warning",
            "",
            errMsg || "获取表单详细信息失败",
          );
          return;
        }
        this.setState({ formSchema: fields, formConfig: datas }, this.forceUpdate());
      },
    );
  };

  handleSave = () => {
    const { dispatch } = this.props;
    const { formConfig } = this.state;
    const newSchema = this.getFormSchemaObject();
    // console.log(newSchema)
    // console.log(formConfig)
    if (!newSchema) {
      return;
    }
    if (!newSchema.properties || Object.keys(newSchema.properties).lenght < 1) {
      this.openNotificationWithIcon("warning", "", "请先配置表单后再保存");
      return;
    }
    if (!formConfig.name || !formConfig.name.trim()) {
      return;
    }
    if (!formConfig.key || !formConfig.key.trim()) {
      return;
    }
    if (!codePattern.test(formConfig.key)) {
      this.openNotificationWithIcon('warning', '', codePatternErrMsg);
      return;
    }
    if (
      formConfig.name.length > 20 ||
      formConfig.key.length > 20 ||
      formConfig.description.length > 100
    ) {
      return;
    }
    formConfig.name = formConfig.name.trim();
    formConfig.key = formConfig.key.trim();
    formConfig.description = formConfig.description.trim();
    // const itemKey = {}; // 控件编码
    let isPass = true;
    let warningMsg = "";
    const arr = Object.keys(newSchema.properties);
    let properties = { ...newSchema.properties };
    while (arr.length > 0) {
      const keys = arr.shift();
      const ele = properties[keys];
      const { title, 'x-component': xComp, 'x-component-props': xCompProps } = ele;
      if (!title && xComp !== 'Grid') {
        const { title: xCompTitle } = xCompProps;
        if (xComp !== 'Card' || !xCompTitle) {
          warningMsg = "控件标题不能为空";
          isPass = false;
          break;
        }
      }

      if (xComp === 'Grid' && ele.properties) {
        arr.push(...Object.keys(ele.properties));
        properties = {
          ...properties,
          ...ele.properties,
        }
      }
      if (xComp === 'Card') {
        const childProperties = getCardChildProperties(ele);
        arr.push(...Object.keys(childProperties));
        properties = {
          ...properties,
          ...childProperties,
        }
      }
      // if (itemKey[keys]) {
      //   warningMsg = "控件编码不唯一";
      //   isPass = false;
      //   break;
      // }
      if (ele['x-component'] === 'Select' || ele['x-component'] === 'CheckboxGroup' || ele['x-component'] === 'RadioGroup') {
        if (!ele.enum) {
          warningMsg = "选项配置不能为空";
          isPass = false;
          break;
        } else {
          let isEmpty = false;
          const filterOp = ele.enum.filter((item, index) => {
            const newArr = ele.enum.slice(index + 1);
            if (!item.label || !item.value) {
              isEmpty = true;
            }
            return newArr.some((oitem) => oitem.value === item.value);
          });
          if (isEmpty) {
            warningMsg = `请填写完整 '${title}' 选项配置信息`;
            isPass = false;
            break;
          }
          if (filterOp && filterOp.length > 0) {
            warningMsg = `${title} 选项配置中的选项值不唯一`;
            isPass = false;
            break;
          }
        }
      }
      // itemKey[keys] = ele;
    }
    if (!isPass) {
      this.openNotificationWithIcon("warning", "", warningMsg);
      return;
    }
    this.isSaving = true;
    dispatch({
      type: "FormBuilder/editSave",
      payload: { ...formConfig, fields: newSchema },
    }).then(({ errCode, errMsg }) => {
      this.isSaving = false;
      if (errCode !== 0) {
        this.openNotificationWithIcon("warning", "", errMsg || "保存失败");
      } else {
        this.openNotificationWithIcon("success", "", "保存成功");
      }
    });
  }

  // 预览
  previewForm = () => {
    const formConfig = this.getFormSchemaObject();
    let ok = !!formConfig;
    if (ok) {
      if (Array.isArray(formConfig)) {
        ok = formConfig.length > 0;
      } else if (!formConfig.properties || Object.keys(formConfig).length < 1) {
        ok = false;
      }
    }

    if (!ok) {
      this.openNotificationWithIcon(
        "warning",
        "",
        "请先编辑表单控件后再预览",
      );
      return;
    }
    this.formTitle = formConfig.name;
    this.customFormVisible(true);
  };

  customFormVisible = (status) => {
    this.setState({ formVisible: status });
  };

  onPrePage = () => {
    // 反回上一级
    // const { history } = this.props;
    Modal.confirm({
      title: "您有未保存的更改",
      content: "您想如何处理未保存的更改？",
      cancelText: "放弃更改",
      okText: "继续编辑",
      onOk() { },
      onCancel() {
        // history.push("/flowmanage/formconfigure");
        // 此页面引用了@ali-dayu/form-editor v0.0.8，对antdv4强依赖导致覆盖了项目中antdv3的样式，需重新加载html
        // 去除antdv4的相关css
        location.href = `${window.routerBase || '/'}flowmanage/formconfigure`;
      },
    });
  };

  handleFormChange = (formConfig = {}) => {
    this.setState({ formConfig });
  };

  getFormSchemaObject = () => {
    const { formSchema } = this.state;
    let newSchema = formSchema;
    if (typeof formSchema === 'string') {
      try {
        newSchema = JSON.parse(formSchema);
      } catch (e) {
        this.openNotificationWithIcon(
          "warning",
          "",
          "当前JSON格式有误，请更正后再重新执行",
        );
        return false;
      }
    }
    return newSchema;
  }

  render() {
    const {
      formSchema,
      formVisible,
      CustomSetterMap,
      CustomWidgetMap,
    } = this.state;
    // const { FormBuilderStore } = this.props;
    const { loading } = this.props;
    const createLoading = loading.effects["FormBuilder/getFormDetail"];
    const { dispatch } = this.props;
    const dataLoading = loading.effects["FormSelectModel/preRequestOuterData"];
    return (
      <Spin spinning={createLoading}>
        <div className={styles.builder_box}>
          <FormTopBar
            className={styles.form_topbar}
            previewForm={this.previewForm}
            formConfig={{}}
            onPrePage={this.onPrePage}
            onSave={this.handleSave}
          />
          <FormEditor
            schema={formSchema}
            widgetIconUrl="//at.alicdn.com/t/font_1955878_2vjl1gshj2g.js"
            widgetMap={CustomWidgetMap}
            setterMap={CustomSetterMap}
            setterPlaceholder={<Empty description="未选中任何控件" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            customBars={[
              // { text: <span>保存</span>, behavior: 'custom', onClick: this.handleSave },
              // { text: <span>预览</span>, behavior: 'custom', onClick: this.previewForm },
            ]}
            onChange={(value) => {
              this.setState({ formSchema: value })
            }}
          />
          {formVisible && (
            <CustomForm
              title={this.formTitle}
              visible={formVisible}
              confirmLoading={false}
              onOk={() => this.customFormVisible(false)}
              isView
              /*
              editable={false}
              initialValues={{ fieldid_1zju2favls000: [
                {
                    "name": "a.txt",
                    "datas": "test/20210622/628da94c-6089-493c-b7f7-aea722fd9753_a.txt"
                },
                {
                    "name": "upload.mp4",
                    "datas": "test/20210622/a52f66d1-5b22-40e2-9f3d-b7a99cd257d7_upload.mp4"
                },
                {
                    "name": "a.txt",
                    "datas": "test/20210622/a4c1f677-f372-4bc1-ac23-58049d377c21_a.txt"
                }
              ]}}
              onOk={(values) => {
                console.log(values);
                // this.customFormVisible(false);
              }}
              */
              // editable={((window.setEdit = (e) => this.setState({ editable: e })), !!this.state.editable)}
              onCancel={() => this.customFormVisible(false)}
              formConfigData={this.getFormSchemaObject()}
              dispatch={dispatch}
              dataLoading={dataLoading}
              // showMobile
            />
          )}
        </div>
      </Spin>
    );
  }
}
export default FormBuilder;
